﻿using System;
using Best.SmartCms.Dao;
using Best.SmartCms.Domain;
using Best.SmartCms.Dto.Enums;
using Best.SmartCms.Dto.Login;
using Best.SmartCms.Service.BizException;
using Best.SmartCms.Service.Common;
using Best.SmartCms.Utility;
using Microsoft.AspNetCore.Hosting;

namespace Best.SmartCms.Service.Security
{
    /// <summary>
    /// 
    /// </summary>
    public class LoginService : IService
    {
        private readonly UserDao _userDao;
        private readonly LoginTokenService _loginTokenService;
        private readonly IHostingEnvironment _hostingEnvironment;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="mySqlDbContext"></param>
        /// <param name="loginTokenService"></param>
        /// <param name="hostingEnvironment"></param>
        public LoginService(MySqlDbContext mySqlDbContext, LoginTokenService loginTokenService, IHostingEnvironment hostingEnvironment)
        {
            _userDao = new UserDao(mySqlDbContext);
            _loginTokenService = loginTokenService;
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 登入
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public string Login(LoginRequestDto q)
        {
            var user = _userDao.FindByPhone(q.Phone);
            if (user == null)
            {
                throw new LoginedException("用户名或密码错误");
            }

            if (!Md5Utility.EncryptVerify(user.Password, user.PasswordSalt, q.Password))
            {
                throw new LoginedException("用户名或密码错误");
            }

            if (!user.Enabled)
            {
                throw new LoginedException("该用户未启用");
            }

            if (q.Source == RequestSourceEnum.None || Enum.IsDefined(typeof(RequestSourceEnum), q.Source) == false)
            {
                q.Source = RequestSourceEnum.MiniProgram;
            }

            var token = _loginTokenService.CreateToken(user, q.Source);
            return token;
        }
    }
}
